//
//  WebVIewVC.m
//  iceTearsTest
//
//  Created by 张飞跃 on 16/4/25.
//  Copyright © 2016年 张飞跃. All rights reserved.
//

#import "WebVIewVC.h"

@interface WebVIewVC ()

@end

@implementation WebVIewVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    NSLog(@"1------%@",[self whatismyipdotcom]);
    
    NSLog(@"2------%@",[self localWiFiIPAddress]);
    
    NSLog(@"3------%@",[self hostname]);
    
    NSLog(@"4------%@",[self getIPAddressForHost:@"www.91als.com"]);
    
    NSLog(@"5------%@",[self localIPAddress]);
    
    //[self ipip1];
}

- (void)ipip1

{

    NSURL *url = [NSURL URLWithString:@"http://fw.qq.com/ipaddress"];
    
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request setHTTPMethod:@"GET"];
    
    [request setTimeoutInterval:8.0f];
    
    NSHTTPURLResponse *response;
    
    
    
    //返回的是GBK编码
    
    //NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:@""responseerror:nil];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    if (200 == [response statusCode]) {
        
        //直接转,将会产生乱码或者字符串为空    NSUTF8StringEncoding
        
        NSString *temp1 = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
        
        //                               NSASCIIStringEncoding
        
        NSString *temp2 = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
        
        NSLog(@"---------temp1---%@",temp1);
        
        NSLog(@"---------temp2---%@",temp2);
        
        NSLog(@"-------------------------------------");
        
        
        
        // 一、 GBK编码 (通过CFStringCreateWithBytes转码)

        
       CFStringRef GBKCFstirng =CFStringCreateWithBytes(NULL,[returnData bytes], [returnData length],kCFStringEncodingGB_18030_2000,false);
        
        
        
      //  NSString *gbkNSString1 = (NSString *)GBKCFStirng;
        NSString *gbkNSString1 = (__bridge NSString *)GBKCFstirng;
        NSLog(@"--gbkNSString1---%@",gbkNSString1);
        
        
        
        // 二、 GBK编码 (通过CFStringConvertEncodingToNSStringEncoding转码)
        
        NSStringEncoding nsEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        
        NSString *gbkNSString2 = [[NSString alloc] initWithData:returnData encoding:nsEncoding];
        
        NSLog(@"--gbkNSString2---%@",gbkNSString2);
        
        
        
        NSLog(@"-------------------------------------");
        
        
        
        //转成NSUTF8StringEncoding的字符串
        
        NSData *tempdata = [gbkNSString1 dataUsingEncoding:NSUTF8StringEncoding];
        
        NSString *UTF8_NSString = [[NSString alloc] initWithData:tempdata
                                                        encoding:NSUTF8StringEncoding];
        
        NSLog(@"--UTF8_NSString--%@",UTF8_NSString);       
        
    }
    
}


//ip等信息
- (NSString *) whatismyipdotcom
{
    NSError *error;
    NSURL *ipURL = [NSURL URLWithString:@"https://fw.qq.com/ipaddress"];
    NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:1 error:&error];
    return ip ? ip : [error localizedDescription];
}
//获取本地wifi的ip地址
- (NSString *) localWiFiIPAddress
{
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;
    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            // the second test keeps from picking up the loopback address
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                if ([name isEqualToString:@"en0"])  // Wi-Fi adapter
                    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return nil;
}

//  NSString和Address转换
+ (NSString *) stringFromAddress: (const struct sockaddr *) address
{
    if(address && address->sa_family == AF_INET) {
        const struct sockaddr_in* sin = (struct sockaddr_in*) address;
        return [NSString stringWithFormat:@"%@:%d", [NSString stringWithUTF8String:inet_ntoa(sin->sin_addr)], ntohs(sin->sin_port)];
    }
    
    return nil;
}

+ (BOOL)addressFromString:(NSString *)IPAddress address:(struct sockaddr_in *)address
{
    if (!IPAddress || ![IPAddress length]) {
        return NO;
    }
    
    memset((char *) address, sizeof(struct sockaddr_in), 0);
    address->sin_family = AF_INET;
    address->sin_len = sizeof(struct sockaddr_in);
    
    int conversionResult = inet_aton([IPAddress UTF8String], &address->sin_addr);
    if (conversionResult == 0) {
        NSAssert1(conversionResult != 1, @"Failed to convert the IP address string into a sockaddr_in: %@", IPAddress);
        return NO;
    }
    
    return YES;
}

//获取host属性

- (NSString *) hostname
{
    char baseHostName[256]; // Thanks, Gunnar Larisch
    int success = gethostname(baseHostName, 255);
    if (success != 0) return nil;
    baseHostName[255] = '/0';
    
#if TARGET_IPHONE_SIMULATOR
    return [NSString stringWithFormat:@"%s", baseHostName];
#else
    return [NSString stringWithFormat:@"%s.local", baseHostName];
#endif
}
//从host获取地址
- (NSString *) getIPAddressForHost: (NSString *) theHost
{
    struct hostent *host = gethostbyname([theHost UTF8String]);
    if (!host) {herror("resolv"); return NULL; }
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    NSString *addressString = [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
    return addressString;
}

//这是本地host的IP地址
- (NSString *) localIPAddress
{
    struct hostent *host = gethostbyname([[self hostname] UTF8String]);
    if (!host) {herror("resolv"); return nil;}
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
